<template>
  <div class="account-settings-info-view">
    <a-spin :spinning="spinning">
      <a-row :gutter="16">
        <a-col :md="24" :lg="16">
          <a-form-model ref="form" :model="model" :rules="validatorRules" layout="vertical">
            <a-form-model-item label="用户姓名" prop="realname">
              <a-input placeholder="请输入用户姓名" v-model="model.realname" />
            </a-form-model-item>

            <a-form-model-item label="工号/警号" prop="workNo">
              <a-input placeholder="请输入工号/警号" v-model="model.workNo" />
            </a-form-model-item>
            <a-form-model-item label="出生日期" prop="birthday">
              <a-date-picker
                style="width: 100%"
                placeholder="请选择出生日期"
                v-model="model.birthday"
                :format="dateFormat"
                :allowClear="false"
              />
            </a-form-model-item>

            <a-form-model-item label="性别">
              <a-select v-model="model.sex" placeholder="请选择性别" :getPopupContainer="(target) => target.parentNode">
                <a-select-option :value="1">男</a-select-option>
                <a-select-option :value="2">女</a-select-option>
              </a-select>
            </a-form-model-item>

            <a-form-model-item label="邮箱" prop="email">
              <a-input placeholder="请输入邮箱" v-model="model.email" />
            </a-form-model-item>

            <a-form-model-item label="手机号码" prop="phone">
              <a-input placeholder="请输入手机号码" v-model="model.phone" />
            </a-form-model-item>

            <a-form-model-item label="座机" prop="telephone">
              <a-input placeholder="请输入座机" v-model="model.telephone" />
            </a-form-model-item>

            <a-form-model-item>
              <a-button type="primary" @click="handleSubmit" :loading="confirmLoading" :disabled="spinning"
                >提交</a-button
              >
              <a-button style="margin-left: 8px" @click="handleCancel">取消</a-button>
            </a-form-model-item>
          </a-form-model>
        </a-col>
        <a-col :md="24" :lg="8" :style="{ minHeight: '180px' }">
          <!-- <div class="ant-upload-preview" @click="$refs.modal.edit(1)">
          <a-icon type="cloud-upload-o" class="upload-icon" />
          <div class="mask">
            <a-icon type="plus" />
          </div>
          <img :src="option.img" />
        </div> -->
          <j-image-upload class="avatar-uploader" text="上传" v-model="model.avatar" style="margin-left: 10%" />
        </a-col>
      </a-row>
    </a-spin>
    <!-- <avatar-modal ref="modal"> </avatar-modal> -->
  </div>
</template>

<script>
import { getAction, getFileAccessHttpUrl } from '@/api/manage'
// import AvatarModal from './AvatarModal'
import { USER_INFO } from '@/store/mutation-types'
import { queryById, editUser, queryUserRole, duplicateCheck } from '@/api/api'

export default {
  // components: {
  //   AvatarModal,
  // },
  inject: ['closeCurrent'],
  data() {
    return {
      userId: '', //保存用户id
      dateFormat: 'YYYY-MM-DD',
      preview: {},
      option: {
        img: '/avatar2.jpg',
        info: true,
        size: 1,
        outputType: 'jpeg',
        canScale: false,
        autoCrop: true,
        // 只有自动截图开启 宽度高度才生效
        autoCropWidth: 180,
        autoCropHeight: 180,
        fixedBox: true,
        // 开启宽度和高度比例
        fixed: true,
        fixedNumber: [1, 1],
      },
      validatorRules: {
        realname: [{ required: true, message: '请输入用户名称!' }],
        phone: [{ required: true, message: '请输入手机号!' }, { validator: this.validatePhone }],
        email: [{ validator: this.validateEmail }],
        roles: {},
        workNo: [{ required: true, message: '请输入工号' }, { validator: this.validateWorkNo }],
        telephone: [{ pattern: /^0\d{2,3}-[1-9]\d{6,7}$/, message: '请输入正确的座机号码' }],
      },
      spinning: false,
      confirmLoading: false,
      model: {},
      url: {
        userWithDepart: '/sys/user/userDepartList', // 引入为指定用户查看部门信息需要的url
      }
    }
  },
  async mounted() {
    let id = this.$ls.get(USER_INFO).id
    if (!id) return
    this.spinning = true
    Promise.all([
      this.getQueryById(id),
      this.getUserRoles(id),
      this.getUserDeparts(id)
    ]).then(() => {
      this.spinning = false
    })
  },
  methods: {
    async getQueryById(id) {
      this.userId = id
      let res = await queryById({ id: id })
      if (res.success) {
        this.model = Object.assign({}, this.model, res.result)
        // let url = getFileAccessHttpUrl(val.avatar);
        // this.$set(this.option, 'img', url)
      } else {
        this.$message.warning(res.message)
      }
    },
    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.confirmLoading = true
          editUser(this.model)
            .then((res) => {
              if (res.success) {
                this.$message.success(res.message)
              } else {
                this.$message.warning(res.message)
              }
              this.confirmLoading = false
            })
            .catch(() => {
              this.confirmLoading = false
            })
        } else {
          return false
        }
      })
    },
    handleCancel() {
      this.closeCurrent()
    },
    validatePhone(rule, value, callback) {
      if (!value) {
        callback()
      } else {
        if (new RegExp(/^1[3|4|5|6|7|8|9][0-9]\d{8}$/).test(value)) {
          var params = {
            tableName: 'sys_user',
            fieldName: 'phone',
            fieldVal: value,
            dataId: this.userId,
          }
          duplicateCheck(params).then((res) => {
            if (res.success) {
              callback()
            } else {
              callback('手机号已存在!')
            }
          })
        } else {
          callback('请输入正确格式的手机号码!')
        }
      }
    },
    validateEmail(rule, value, callback) {
      if (!value) {
        callback()
      } else {
        if (
          new RegExp(
            /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
          ).test(value)
        ) {
          var params = {
            tableName: 'sys_user',
            fieldName: 'email',
            fieldVal: value,
            dataId: this.userId,
          }
          duplicateCheck(params).then((res) => {
            console.log(res)
            if (res.success) {
              callback()
            } else {
              callback('邮箱已存在!')
            }
          })
        } else {
          callback('请输入正确格式的邮箱!')
        }
      }
    },
    validateUsername(rule, value, callback) {
      var params = {
        tableName: 'sys_user',
        fieldName: 'username',
        fieldVal: value,
        dataId: this.userId,
      }
      duplicateCheck(params).then((res) => {
        if (res.success) {
          callback()
        } else {
          callback('用户名已存在!')
        }
      })
    },
    validateWorkNo(rule, value, callback) {
      var params = {
        tableName: 'sys_user',
        fieldName: 'work_no',
        fieldVal: value,
        dataId: this.userId,
      }
      duplicateCheck(params).then((res) => {
        if (res.success) {
          callback()
        } else {
          callback('工号已存在!')
        }
      })
    },
    async getUserRoles(userid) {
      let res = await queryUserRole({ userid: userid })
      if (res.success) {
        this.$set(this.model, 'selectedroles', res.result.join(','))
        console.log('that.model.selectedroles=', this.model.selectedroles)
      }
    },
    async getUserDeparts(userid) {
      let res = await getAction(this.url.userWithDepart, { userId: userid })
      if (res.success) {
        let departOptions = []
        let selectDepartKeys = []
        for (let i = 0; i < res.result.length; i++) {
          selectDepartKeys.push(res.result[i].key)
          //新增负责部门选择下拉框
          departOptions.push({
            value: res.result[i].key,
            label: res.result[i].title,
          })
        }
        this.$set(this.model, 'selecteddeparts', selectDepartKeys.join(','))
        // this.nextDepartOptions=departOptions;
        console.log('this.nextDepartOptions=', this.nextDepartOptions)
      }
    },
  },
}
</script>

<style lang="less" scoped>
.avatar-upload-wrapper {
  height: 200px;
  width: 100%;
}

.ant-upload-preview {
  position: relative;
  margin: 0 auto;
  width: 100%;
  max-width: 180px;
  border-radius: 50%;
  box-shadow: 0 0 4px #ccc;

  .upload-icon {
    position: absolute;
    top: 0;
    right: 10px;
    font-size: 1.4rem;
    padding: 0.5rem;
    background: rgba(222, 221, 221, 0.7);
    border-radius: 50%;
    border: 1px solid rgba(0, 0, 0, 0.2);
  }
  .mask {
    opacity: 0;
    position: absolute;
    background: rgba(0, 0, 0, 0.4);
    cursor: pointer;
    transition: opacity 0.4s;

    &:hover {
      opacity: 1;
    }

    i {
      font-size: 2rem;
      position: absolute;
      top: 50%;
      left: 50%;
      margin-left: -1rem;
      margin-top: -1rem;
      color: #d6d6d6;
    }
  }

  img,
  .mask {
    width: 100%;
    max-width: 180px;
    height: 100%;
    border-radius: 50%;
    overflow: hidden;
  }
}

/deep/.ant-upload-list-picture-card {
  .ant-upload-list-item {
    width: 170px;
    height: 170px;
  }
}
/deep/.ant-upload.ant-upload-select-picture-card {
  width: 170px;
  height: 170px;
}
</style>